/*
 * InternalRegisterSerializer.cpp
 *
 *  Created on: Nov 2, 2012
 *      Author: m
 */

#include "InternalRegisterSerializer.h"

using physical::byte;
using physical::byteStream;

InternalRegisterSerializer::InternalRegisterSerializer()
{
}

InternalRegisterSerializer::~InternalRegisterSerializer()
{
}

size_t InternalRegisterSerializer::serialize( const _T& element, byteStream block )
{
    byte* blockPtr = block;
    size_t bytesUsed;
    size_t totalBytesUsed = 0;

    NodeID_t value;

    value = element.getValue();

    // serializo la key
    bytesUsed = m_keySerializer.serialize( element.getKey(), blockPtr );
    totalBytesUsed += bytesUsed;
    blockPtr += bytesUsed;

    // Serializo el nº de nodo
    memcpy( blockPtr, &value, sizeof( NodeID_t ) );
    bytesUsed = sizeof( NodeID_t );
    totalBytesUsed += bytesUsed;
    blockPtr += bytesUsed;

    return totalBytesUsed;
}

size_t InternalRegisterSerializer::deserialize(
        const physical::byteStream block, _T& element )
{
    const byte* blockPtr = block;
    size_t bytesUsed;
    size_t totalBytesUsed = 0;
    std::string key;
    NodeID_t value;

    // serializo la key
    bytesUsed = m_keySerializer.deserialize( blockPtr, key );
    totalBytesUsed += bytesUsed;
    blockPtr += bytesUsed;

    // Serializo el nº de nodo
    memcpy( &value, blockPtr, sizeof( NodeID_t ) );
    bytesUsed = sizeof( NodeID_t );
    totalBytesUsed += bytesUsed;
    blockPtr += bytesUsed;

    element = _T( key,value );

    return totalBytesUsed;
}

size_t InternalRegisterSerializer::getSize(
        const _T& element )
{
    size_t totalBytesUsed = 0;

    // calculo el tamaño de la key serializada
    totalBytesUsed += m_keySerializer.getSize( element.getKey() );

    // calculo el tamaño del valor (referencia a nodo) serializado
    totalBytesUsed += sizeof( NodeID_t );

    return totalBytesUsed;
}

size_t InternalRegisterSerializer::computeSize(
        const _T& element )
{
    return this->getSize( element );
}

size_t InternalRegisterSerializer::serialize(
        const _T_ptr& elementPtr, physical::byteStream block )
{
    return this->serialize( *elementPtr, block );
}

size_t InternalRegisterSerializer::deserialize(
        const physical::byteStream block, _T_ptr& elementPtr )
{
    // todo: arreglar esto que queda feo
    elementPtr.reset( new BPlusSimpleRegisterTemplate < std::string, NodeID_t >( "", 0 ) );
    return this->deserialize( block, *elementPtr );
}

size_t InternalRegisterSerializer::getSize(
        const _T_ptr& elementPtr )
{
    return this->computeSize( *elementPtr );
}

size_t InternalRegisterSerializer::computeSize(
        const _T_ptr& elementPtr )
{
    return this->getSize( elementPtr );
}
